<template>
  <div class="locks-management">
    <div class="page-header">
      <h2>门锁管理</h2>
      <Space>
        <Button @click="refreshLocks">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新状态
        </Button>
        <Button type="primary" @click="showAddLockModal = true">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加门锁
        </Button>
      </Space>
    </div>

    <!-- 门锁统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="门锁总数"
          :value="statistics.totalLocks"
          :change="statistics.totalChange"
          icon="ant-design:lock-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线门锁"
          :value="statistics.onlineLocks"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="离线门锁"
          :value="statistics.offlineLocks"
          :change="statistics.offlineChange"
          icon="ant-design:close-circle-outlined"
          color="#f5222d"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日开门"
          :value="statistics.todayOpens"
          :change="statistics.opensChange"
          icon="ant-design:key-outlined"
          color="#722ed1"
        />
      </Col>
    </Row>

    <!-- 门锁状态地图 -->
    <Card title="门锁状态分布" class="map-card">
      <div class="map-container">
        <div class="map-placeholder">
          <IconifyIcon
            icon="ant-design:environment-outlined"
            class="map-icon"
          />
          <p>门锁分布地图</p>
          <p class="map-desc">显示各楼层门锁状态和分布情况</p>
        </div>
      </div>
    </Card>

    <!-- 门锁列表 -->
    <Card title="门锁列表" class="locks-list-card">
      <div class="list-header">
        <Form layout="inline" :model="searchForm" class="search-form">
          <FormItem label="房间号">
            <Input
              v-model:value="searchForm.roomNumber"
              placeholder="请输入房间号"
              allow-clear
            />
          </FormItem>
          <FormItem label="门锁状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="online">在线</SelectOption>
              <SelectOption value="offline">离线</SelectOption>
              <SelectOption value="locked">已锁定</SelectOption>
              <SelectOption value="unlocked">已解锁</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="楼层">
            <Select
              v-model:value="searchForm.floor"
              placeholder="请选择楼层"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="1">1楼</SelectOption>
              <SelectOption value="2">2楼</SelectOption>
              <SelectOption value="3">3楼</SelectOption>
              <SelectOption value="4">4楼</SelectOption>
              <SelectOption value="5">5楼</SelectOption>
            </Select>
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleSearch">
                <IconifyIcon icon="ant-design:search-outlined" />
                搜索
              </Button>
              <Button @click="handleReset">
                <IconifyIcon icon="ant-design:reload-outlined" />
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="columns"
        :data-source="filteredLocks"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'roomNumber'">
            <div class="room-info">
              <div class="room-number">{{ record.roomNumber }}</div>
              <div class="room-type">{{ record.roomType }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'lockState'">
            <Tag :color="getLockStateColor(record.lockState)">
              {{ getLockStateText(record.lockState) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'battery'">
            <div class="battery-info">
              <Progress
                :percent="record.battery"
                :stroke-color="getBatteryColor(record.battery)"
                :show-info="false"
                size="small"
              />
              <span class="battery-text">{{ record.battery }}%</span>
            </div>
          </template>
          <template v-else-if="column.key === 'lastOpen'">
            <div class="open-info">
              <div class="open-time">{{ record.lastOpenTime }}</div>
              <div class="open-user">{{ record.lastOpenUser }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewLock(record)">
                查看
              </Button>
              <Button
                v-if="record.lockState === 'locked'"
                type="link"
                size="small"
                @click="unlockDoor(record)"
              >
                开门
              </Button>
              <Button v-else type="link" size="small" @click="lockDoor(record)">
                锁门
              </Button>
              <Button
                type="link"
                size="small"
                @click="managePermissions(record)"
              >
                权限
              </Button>
              <Button type="link" size="small" @click="viewHistory(record)">
                记录
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 开门记录 -->
    <Card title="开门记录" class="records-card">
      <div class="records-header">
        <Space>
          <Button
            v-for="period in recordPeriods"
            :key="period.value"
            :type="selectedPeriod === period.value ? 'primary' : 'default'"
            size="small"
            @click="selectedPeriod = period.value"
          >
            {{ period.label }}
          </Button>
        </Space>
      </div>
      <Table
        :columns="recordColumns"
        :data-source="openRecords"
        :pagination="recordPagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'roomNumber'">
            <span class="room-number">{{ record.roomNumber }}</span>
          </template>
          <template v-else-if="column.key === 'openMethod'">
            <Tag :color="getMethodColor(record.openMethod)">
              {{ getMethodText(record.openMethod) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'userType'">
            <Tag :color="getUserTypeColor(record.userType)">
              {{ getUserTypeText(record.userType) }}
            </Tag>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 添加门锁弹窗 -->
    <Modal
      v-model:open="showAddLockModal"
      title="添加门锁"
      width="600px"
      @ok="handleSaveLock"
      @cancel="handleCancelLock"
    >
      <Form
        ref="lockFormRef"
        :model="lockForm"
        :rules="lockRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="房间号" name="roomNumber">
              <Input
                v-model:value="lockForm.roomNumber"
                placeholder="请输入房间号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="房间类型" name="roomType">
              <Select
                v-model:value="lockForm.roomType"
                placeholder="请选择房间类型"
              >
                <SelectOption value="standard">标准间</SelectOption>
                <SelectOption value="deluxe">豪华间</SelectOption>
                <SelectOption value="suite">套房</SelectOption>
                <SelectOption value="office">办公室</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="门锁型号" name="model">
              <Input
                v-model:value="lockForm.model"
                placeholder="请输入门锁型号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="门锁厂商" name="manufacturer">
              <Input
                v-model:value="lockForm.manufacturer"
                placeholder="请输入门锁厂商"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="IP地址" name="ipAddress">
              <Input
                v-model:value="lockForm.ipAddress"
                placeholder="请输入IP地址"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="门锁状态" name="status">
              <Select
                v-model:value="lockForm.status"
                placeholder="请选择门锁状态"
              >
                <SelectOption value="online">在线</SelectOption>
                <SelectOption value="offline">离线</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="lockForm.remarks"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

// 状态管理
const loading = ref(false);
const showAddLockModal = ref(false);
const isEdit = ref(false);
const selectedPeriod = ref('today');

// 表单引用
const lockFormRef = ref();

// 统计数据
const statistics = reactive({
  totalLocks: 45,
  totalChange: 2,
  onlineLocks: 42,
  onlineChange: 1,
  offlineLocks: 3,
  offlineChange: -1,
  todayOpens: 156,
  opensChange: 12,
});

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  status: '',
  floor: '',
});

// 门锁表单
const lockForm = reactive({
  roomNumber: '',
  roomType: '',
  model: '',
  manufacturer: '',
  ipAddress: '',
  status: 'online',
  remarks: '',
});

// 表单验证规则
const lockRules = {
  roomNumber: [{ required: true, message: '请输入房间号' }],
  roomType: [{ required: true, message: '请选择房间类型' }],
  model: [{ required: true, message: '请输入门锁型号' }],
  ipAddress: [{ required: true, message: '请输入IP地址' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const recordPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 记录时间段
const recordPeriods = [
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '全部', value: 'all' },
];

// 门锁数据
const locks = ref([
  {
    id: 1,
    roomNumber: '101',
    roomType: '标准间',
    status: 'online',
    lockState: 'locked',
    battery: 85,
    lastOpenTime: '2024-01-19 14:30',
    lastOpenUser: '张三',
    model: 'SL-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.101',
  },
  {
    id: 2,
    roomNumber: '102',
    roomType: '标准间',
    status: 'online',
    lockState: 'unlocked',
    battery: 92,
    lastOpenTime: '2024-01-19 15:20',
    lastOpenUser: '李四',
    model: 'SL-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.102',
  },
  {
    id: 3,
    roomNumber: '201',
    roomType: '豪华间',
    status: 'offline',
    lockState: 'locked',
    battery: 45,
    lastOpenTime: '2024-01-19 12:15',
    lastOpenUser: '王五',
    model: 'SL-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.201',
  },
  {
    id: 4,
    roomNumber: '301',
    roomType: '套房',
    status: 'online',
    lockState: 'locked',
    battery: 78,
    lastOpenTime: '2024-01-19 16:45',
    lastOpenUser: '赵六',
    model: 'SL-2000',
    manufacturer: '海康威视',
    ipAddress: '192.168.1.301',
  },
]);

// 开门记录数据
const openRecords = ref([
  {
    id: 1,
    roomNumber: '101',
    openTime: '2024-01-19 15:30',
    openMethod: 'card',
    userType: 'tenant',
    userName: '张三',
    duration: '2分钟',
  },
  {
    id: 2,
    roomNumber: '102',
    openTime: '2024-01-19 15:20',
    openMethod: 'password',
    userType: 'staff',
    userName: '李四',
    duration: '1分钟',
  },
  {
    id: 3,
    roomNumber: '201',
    openTime: '2024-01-19 15:15',
    openMethod: 'remote',
    userType: 'admin',
    userName: '王五',
    duration: '30秒',
  },
  {
    id: 4,
    roomNumber: '301',
    openTime: '2024-01-19 15:10',
    openMethod: 'fingerprint',
    userType: 'tenant',
    userName: '赵六',
    duration: '3分钟',
  },
]);

// 表格列定义
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 120,
  },
  {
    title: '门锁状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '锁定状态',
    dataIndex: 'lockState',
    key: 'lockState',
    width: 100,
  },
  {
    title: '电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 120,
  },
  {
    title: '最后开门',
    dataIndex: 'lastOpen',
    key: 'lastOpen',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 记录表格列定义
const recordColumns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '开门时间',
    dataIndex: 'openTime',
    key: 'openTime',
    width: 150,
  },
  {
    title: '开门方式',
    dataIndex: 'openMethod',
    key: 'openMethod',
    width: 100,
  },
  {
    title: '用户类型',
    dataIndex: 'userType',
    key: 'userType',
    width: 100,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 100,
  },
  {
    title: '开门时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 100,
  },
];

// 过滤后的门锁数据
const filteredLocks = computed(() => {
  let result = locks.value;

  if (searchForm.roomNumber) {
    result = result.filter((item) =>
      item.roomNumber
        .toLowerCase()
        .includes(searchForm.roomNumber.toLowerCase()),
    );
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.floor) {
    result = result.filter((item) =>
      item.roomNumber.startsWith(searchForm.floor),
    );
  }

  return result;
});

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    online: 'green',
    offline: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
  };
  return texts[status] || status;
};

const getLockStateColor = (state: string) => {
  const colors: Record<string, string> = {
    locked: 'red',
    unlocked: 'green',
  };
  return colors[state] || 'default';
};

const getLockStateText = (state: string) => {
  const texts: Record<string, string> = {
    locked: '已锁定',
    unlocked: '已解锁',
  };
  return texts[state] || state;
};

const getBatteryColor = (battery: number) => {
  if (battery > 80) return '#52c41a';
  if (battery > 50) return '#faad14';
  return '#f5222d';
};

const getMethodColor = (method: string) => {
  const colors: Record<string, string> = {
    card: 'blue',
    password: 'green',
    fingerprint: 'purple',
    remote: 'orange',
  };
  return colors[method] || 'default';
};

const getMethodText = (method: string) => {
  const texts: Record<string, string> = {
    card: '门卡',
    password: '密码',
    fingerprint: '指纹',
    remote: '远程',
  };
  return texts[method] || method;
};

const getUserTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    tenant: 'blue',
    staff: 'green',
    admin: 'purple',
  };
  return colors[type] || 'default';
};

const getUserTypeText = (type: string) => {
  const texts: Record<string, string> = {
    tenant: '租客',
    staff: '员工',
    admin: '管理员',
  };
  return texts[type] || type;
};

// 事件处理函数
const refreshLocks = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('门锁状态刷新完成');
  }, 1000);
};

const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    status: '',
    floor: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSaveLock = async () => {
  try {
    await lockFormRef.value.validate();
    if (isEdit.value) {
      message.success('门锁信息更新成功');
    } else {
      message.success('门锁添加成功');
    }
    showAddLockModal.value = false;
    resetLockForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancelLock = () => {
  showAddLockModal.value = false;
  resetLockForm();
};

const viewLock = (record: any) => {
  message.info(`查看门锁详情: ${record.roomNumber}`);
};

const unlockDoor = (record: any) => {
  message.success(`门锁"${record.roomNumber}"开门成功`);
};

const lockDoor = (record: any) => {
  message.success(`门锁"${record.roomNumber}"锁门成功`);
};

const managePermissions = (record: any) => {
  message.info(`管理门锁权限: ${record.roomNumber}`);
};

const viewHistory = (record: any) => {
  message.info(`查看开门记录: ${record.roomNumber}`);
};

const resetLockForm = () => {
  Object.assign(lockForm, {
    roomNumber: '',
    roomType: '',
    model: '',
    manufacturer: '',
    ipAddress: '',
    status: 'online',
    remarks: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = locks.value.length;
  recordPagination.total = openRecords.value.length;
});
</script>

<style scoped>
.locks-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.map-card {
  margin-bottom: 24px;
}

.map-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.map-placeholder {
  color: #999;
  text-align: center;
}

.map-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.map-desc {
  margin-top: 8px;
  font-size: 14px;
}

.locks-list-card {
  margin-bottom: 24px;
}

.list-header {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-number {
  font-weight: 500;
  color: #1890ff;
}

.room-type {
  font-size: 12px;
  color: #999;
}

.battery-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.battery-text {
  min-width: 30px;
  font-size: 12px;
  font-weight: 500;
}

.open-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.open-time {
  font-size: 12px;
  color: #666;
}

.open-user {
  font-size: 12px;
  color: #999;
}

.records-card {
  margin-bottom: 16px;
}

.records-header {
  margin-bottom: 16px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
